import { _decorator, Component, Node,Prefab,instantiate,Vec3,v3,tween,UITransform} from 'cc';
import Util from "./Util";

const { ccclass, property } = _decorator;

@ccclass('MoneyAnim')
export class MoneyAnim extends Component {
    @property({type:Prefab})
    coinPrefab: Prefab = null;

    @property({type:Node})
    dstNode:Node=null;

    @property({type:Node})
    attachNode:Node=null;

    private dstLastScaleTime:number=0;

    private dstDefaultScale:Vec3=v3(1, 1, 1);

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start () {

    }

    public play(cb:Function=null, num:number=25)
    {

        let coinNum:number=num;
        for(let i=0;i<coinNum;i++)
        {
            let coinObj=instantiate(this.coinPrefab);
            this.attachNode.addChild(coinObj);
            coinObj.setPosition(0,0,0);
        }

        let up:Vec3=v3(0,1,0);

        //let dstPos:Vec3=v3(0,0,0);
        let nodes=[];
        for(let i=0;i<this.attachNode.children.length;i++)
        {
            let randDir:Vec3=v3(0,0,0);
            //方向随机
            let radian:number=Util.randRangeNumber(0, 359);
            radian=radian * Math.PI / 180;
            Vec3.rotateZ(randDir,up,Vec3.ZERO, radian);

            let dis:number=Util.randRangeNumber(80,100);
            randDir.multiplyScalar(dis);

            this.attachNode.children[i].setScale(0.3, 0.3,0.3);

            tween(this.attachNode.children[i]).to(0.4, {scale:v3(0.7, 0.7, 1) , position:randDir}).call(()=>{

            }).start();
            nodes.push(this.attachNode.children[i]);

        }


        let dstWorldPos:Vec3=this.dstNode.getComponent(UITransform).convertToWorldSpaceAR(Vec3.ZERO);
        let dstLocalPos:Vec3=this.node.getComponent(UITransform).convertToNodeSpaceAR(dstWorldPos);
        for(let i=0;i<nodes.length;i++)
        {

            this.scheduleOnce(()=>{

                if(cb!==null)
                    cb();

                //AudioManager.play(AudioClipID.Coin);
                tween(nodes[i]).to(0.3, { position: dstLocalPos}).call(()=>{
                    nodes[i].removeFromParent(true);
                    nodes[i].destroy();
                    this.trigDstNodeScale();
                }).start();


            }, 0.4 + i*0.015);
        }
    }

    public setDstNode(dst:Node)
    {
        this.dstNode=dst;
    }

    public trigDstNodeScale()
    {
        if(Date.now() - this.dstLastScaleTime<110)
            return;
        this.dstLastScaleTime=Date.now();
        tween(this.dstNode).to(0.05, {scale:v3(1.3, 1.3, 1)}).to(0.05,{scale:this.dstDefaultScale}).call(()=>{

        }).start();
    }
}
